package family

import (
	"fmt"
)

// 转换菜单
func (f *Family) transMenu() {
	for id, val := range trans_menu {
		fmt.Printf("------------------------")
		fmt.Printf("%d%s", id+1, val)
		fmt.Println("------------------------")
	}
	fmt.Printf("---------------请选择转账对象或退出(1-%d):", len(trans_menu))
}

// 登记收入或支出
func (f *Family) transaction(option string) {
	user := &f.users[f.uid] //二级引用
	if option == "2" && user.balance == 0 {
		fmt.Printf("---------------------余额为0，无法支出！\n")
		return
	}
	var rec record
	if option == "1" {
		rec.trans_type = income
	} else {
		rec.trans_type = outcome
	}
	fmt.Printf("------------------------请输入%s:", rec.trans_type)
	rec.money = checkMoney(rec.trans_type, user.balance)
	if rec.trans_type == income {
		user.balance += rec.money
	} else {
		user.balance -= rec.money
	}
	rec.balance = user.balance
	fmt.Printf("------------------------请输入备注:")
	fmt.Scanln(&rec.note)
	user.records = append(user.records, rec)
	fmt.Printf("------------------------%s已登记！余额：%.2f\n", rec.trans_type, user.balance)
}

// 查看账单
func (f *Family) bill() {
	records := f.users[f.uid].records
	if len(records) == 0 {
		fmt.Println("------------------------无交易记录！")
		return
	}
	fmt.Println("------------------------收支明细------------------------------")
	fmt.Println("交易类型\t账户余额\t变动金额\t备注")
	for _, v := range records {
		fmt.Printf("  %s\t\t%-8.2f   \t%-8.2f   \t%s\n", v.trans_type, v.balance, v.money, v.note)
	}
	fmt.Println("--------------------------------------------------------------")
}

// 转账
func (f *Family) transMoney(option int) bool {
	if f.users[f.uid].balance == 0 {
		fmt.Printf("---------------------余额为0，无法转账！\n")
		return false
	}
	var name string
	fmt.Printf("----------------请输入%s的用户名:", trans_menu[option-1])
	fmt.Scanln(&name)
	for id, val := range f.users {
		if val.name == name {
			if id == f.uid {
				fmt.Printf("---------------------您不能转给自己！\n")
				return false
			}
			//二级引用，指向用户和转账对象
			user := &f.users[f.uid]
			target := &f.users[id]
			rec_user := record{trans_type: outcome}
			rec_target := record{trans_type: income}
			fmt.Printf("----------------------请输入转账金额:")
			//更新双方的交易记录，交易金额双方一样
			rec_user.money = checkMoney(outcome, user.balance)
			rec_target.money = rec_user.money
			//修改转账人和转账对象的余额
			user.balance -= rec_user.money
			target.balance += rec_user.money
			//更新交易记录中的余额
			rec_user.balance = user.balance
			rec_target.balance = target.balance
			fmt.Printf("------------------------请输入备注:")
			fmt.Scanln(&rec_user.note)
			if rec_user.note == "" {
				rec_user.note = "转给" + trans_menu[option-1]
			}
			rec_target.note = "由" + user.name + "转账"
			user.records = append(user.records, rec_user)
			target.records = append(target.records, rec_target)
			fmt.Println("\t\t转账成功！")
			return true
		}
	}
	fmt.Println("\t\t该用户不存在！")
	return false
}
